import { getUserDetail, getUserProfile, login } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      setToken(token)
    },
    delToken(state) {
      state.token = ''
      removeToken()
    },
    updateUserInfo(state, info) {
      state.userInfo = info
    },
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async initToken(context, data) {
      const res = await login(data)
      // console.log(res)
      context.commit('updateToken', res.data)
      Message.success('登录成功')
    },
    async getUserInfo(context) {
      const res = await getUserProfile()
      // console.log(res)
      const info = await getUserDetail(res.data.userId)
      // console.log(info)
      context.commit('updateUserInfo', { ...res.data, ...info.data })
      return res.data.roles.menus
    },
    logout(context) {
      context.commit('delToken')
      context.commit('delUserInfo')
      // 清空路由
      resetRouter()
    }
  }
}
